﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;

namespace SimpleReactiveObjects
{
    /// <summary>
    /// Represents a writable value and an observable sequence. 
    /// </summary>
    /// <typeparam name="T">The type of value.</typeparam>
    public class ReactiveVariable<T> : IReactiveValue<T>
    {
        private readonly BehaviorSubject<T> subject;
        private readonly IObservable<T> sink;
        private readonly CompositeDisposable subscriptions;

        /// <summary>
        /// Initializes a new instance of the ReactiveVariable&lt;T&gt; class.
        /// </summary>
        public ReactiveVariable()
            : this(default(T))
        {
        }

        /// <summary>
        /// Initializes a new instance of the ReactiveVariable&lt;T&gt; class with the specified value.
        /// </summary>
        /// <param name="value">The initial value.</param>
        public ReactiveVariable(T value)
        {
            this.subject = new BehaviorSubject<T>(value);
            this.sink = subject.DistinctUntilChanged();

            this.subscriptions = new CompositeDisposable()
            {
                subject,
            };
        }

        /// <summary>
        /// Gets or sets the current value.
        /// </summary>
        public T Value
        {
            get
            {
                subscriptions.ThrowIfDisposed();

                var ret = sink.ToEnumerable().First();
                return ret;
            }
            set
            {
                subscriptions.ThrowIfDisposed();

                subject.OnNext(value);
            }
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            subscriptions.ThrowIfDisposed();

            var ret = sink.Subscribe(observer);
            return ret;
        }

        public void Dispose()
        {
            subscriptions.Dispose();
        }

        public override string ToString()
        {
            var ret = Value.ToString();
            return ret;
        }
    }
}
